import datetime

from sqlalchemy import ForeignKey, String, func
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.infrastructure.db.models.base import Base
from src.infrastructure.db.models.m2ms import allowed_ips_orders


class AllowedIP(Base):
    __tablename__ = "allowed_ip"
    __mapper_args__ = {"eager_defaults": True}

    id: Mapped[int] = mapped_column(primary_key=True)
    ip_address: Mapped[str] = mapped_column(String(255), nullable=False, unique=True)
    user = relationship("User", back_populates="allowed_ips")
    user_id: Mapped[int] = mapped_column(ForeignKey("user.id"))
    orders = relationship("Order", secondary=allowed_ips_orders, back_populates="allowed_ips")
    created_at: Mapped[datetime.datetime] = mapped_column(server_default=func.now())

    def __repr__(self):
        return f"<Allowed IP №{self.id} {self.ip_address}>"

    def __str__(self):
        return self.__repr__()
